package com.mhfelipe.tinymce;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

public class PrintPdfServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        String elm1 = request.getParameter("elm1");
        String arquivo = "arquivo.doc";
        boolean podeRecuperar = ServletFileUpload.isMultipartContent(request);

        ServletOutputStream outputStream = response.getOutputStream();


        if (elm1 != null) {
            StringBuilder sb = new StringBuilder("<html><body>");
            sb.append(request.getParameter("elm1"));
            sb.append("</body></html>");

            String text = sb.toString();
            System.out.println(text);
            InputStream inputStream = new ByteArrayInputStream(text.getBytes());

            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document, outputStream);
                document.open();
                XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream, Charset.defaultCharset());
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (podeRecuperar) {

            DiskFileItemFactory fabrica = new DiskFileItemFactory();

            fabrica.setRepository(new File("."));
            FileItemFactory fabItem = fabrica;
            ServletFileUpload upload = new ServletFileUpload(fabItem);

            byte[] bytes;

            try {
                List parseRequest = upload.parseRequest(request);
                for (Object a : parseRequest) {
                    FileItem Fils = (FileItem) a;
                    if (!Fils.isFormField()) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        InputStream inputStream = Fils.getInputStream();


                        byte[] buffer = new byte[2048];
                        int nLidos;
                        while ((nLidos = inputStream.read(buffer)) >= 0) {
                            baos.write(buffer, 0, nLidos);
                        }
                        baos.flush();
                        baos.close();
                        inputStream.close();

                        bytes = baos.toByteArray();

                        HWPFDocument document = new HWPFDocument(new ByteArrayInputStream(bytes));

//        WordExtractor extractor = new WordExtractor(document);

//        String conteudo = extractor.getText();
//        StringBuilder stringBuilder = new StringBuilder(conteudo);

                        Range range = document.getRange();

                        range.insertBefore("TEXTO Inserido antes\n\n");
                        range.insertAfter("\n\nTEXTO Inserido depois");

                        range.replaceText(ENDERECO, "SQN 309 (Definido pelo Sistema).");
                        range.replaceText(NOME, "Marcelo Henrique Felipe (Definidor pelos Sistema).");

                        Document doc = new Document();
                        PdfWriter.getInstance(doc, new FileOutputStream(String.format("novo_arquivo_%d.pdf", new Date().getTime())));
                        doc.open();
                        doc.add(new Paragraph(range.text()));
                        doc.close();

                    }
                }
            } catch (FileUploadException e) {
                System.out.println(e.getLocalizedMessage());
            } catch (Exception e) {
                System.out.println(e.getLocalizedMessage());
            }

        }
    }

    private static String NOME = "___NOME___";
    private static String ENDERECO = "___ENDERECO___";

    public void geraDoc(InputStream inputStream) {
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
